<template>
  <div class="test">
    <h3 class="title">任务列表</h3>
    <div class="desc">
      任务总数：{{ list.length }},还有：{{ getUnfinishTask() }}未完成 【<span
        @click="removeList()"
        >完成</span
      >】
    </div>
    <div class="content-wrap">
      <div class="content" v-for="(item, index) in list" :key="index">
        <input
          type="checkbox"
          :checked="item.isFinished"
          @change="checkItem(index)"
        />
        <span :class="item.isFinished ? 'finish' : ''">
          {{ item.content }}
        </span>
      </div>
    </div>
    <div class="add-content">
      <input type="text" v-model="content" @keyup.13="addcontent()" />
      <button @click="addcontent()">添加</button>
    </div>
  </div>
</template>

<script>
export default {
  name: '',
  data() {
    return {
      list: [
        { content: '设计', isFinished: false },
        { content: '编写页面代码', isFinished: false },
        { content: '编写js代码', isFinished: false },
        { content: '设计产品原型', isFinished: false }
      ],
      content: '',
      tagName: 'input'
    }
  },
  methods: {
    /**
     * 改变状态
     * @date 2021-03-04
     * @param {any} index
     * @returns {any}
     */
    checkItem(index) {
      this.list[index].isFinished = !this.list[index].isFinished
    },
    /**
     * 获得完成的数目
     * @date 2021-03-04
     * @returns {any}
     */
    getUnfinishTask() {
      let sum = 0
      this.list.forEach(item => {
        if (item.isFinished === false) {
          sum++
        }
      })
      return sum
    },
    /**
     * 添加元素
     * @date 2021-03-04
     * @returns {any}
     */
    addcontent() {
      let flag = false
      let reg = /\s/
      if (!this.content | reg.test(this.content)) {
        this.content = ''
        return false
      }
      this.list.forEach(item => {
        if (item.content === this.content) {
          flag = true
        }
      })
      if (flag) {
        this.content = ''
        return false
      }
      let obj = {}
      obj.content = this.content
      obj.isFinished = false
      this.list.push(obj)
      this.content = ''
    },
    /**
     * 删除元素
     * @date 2021-03-04
     * @returns {any}
     */
    removeList() {
      // let newList = []
      // this.list.forEach(item => {
      //   if (item.isFinished === false) {
      //     newList.push(item)
      //   }
      // })
      // this.list = newList

      for (let i = this.list.length - 1; i >= 0; i--) {
        if (this.list[i].isFinished === true) {
          this.list.splice(i, 1)
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
.content-wrap {
  width: 500px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: flex-start;
  .content {
    display: flex;
    justify-content: flex-start;
  }
}
</style>
